<?php
/**
 * I know no such things as genius,it is nothing but labor and diligence.
 *
 * @copyright (c) 2015~2019 BD All rights reserved.
 * @license       http://www.apache.org/licenses/LICENSE-2.0
 * @author        <657306123@qq.com> LXSEA
 */

namespace app\common\traits;

use think\facade\Config;
use think\facade\Env;
use think\Paginator;
use Xin\Thinkphp5\Hint\Facade\Hint;

/**
 * 页面相关的操作
 *
 * @property \think\View  view
 * @property \app\Request request
 * @mixin \think\Controller
 */
trait ViewController{

	/**
	 * 设置信息头
	 *
	 * @param string $title
	 * @param string $keywords
	 * @param string $description
	 * @return static
	 */
	protected function setMeta($title = null, $keywords = null, $description = null){
		if(!empty($title)){
			$this->assign('meta_title', $title." - ".Config::get('web.site_title'));
			$this->assign('page_title', $title);
		}

		$description = $description ? $description : Config::get('web.site_description');
		$this->assign('meta_description', $description);

		if($keywords){
			$keywords .= ','.Config::get('web.site_keywords');
		}else{
			$keywords = Config::get('web.site_keywords');
		}
		$this->assign('meta_keywords', $keywords);

		return $this;
	}

	/**
	 * 设置主题
	 *
	 * @param string $theme
	 * @return static
	 */
	protected function setTheme($theme){
		$theme = Env::get('module_path')."view/{$theme}/";
		$this->view->config('view_path', $theme);

		return $this;
	}

	/**
	 * 加载模板输出
	 *
	 * @access protected
	 * @param string $template 模板文件名
	 * @param array  $vars 模板输出变量
	 * @param array  $config 模板参数
	 * @return mixed
	 */
	protected function fetch($template = '', $vars = [], $config = []){
		if(($this->request->isAjax() || $this->request->isCli())){
			try{
				$reflection = new \ReflectionClass($this->view);
				$dataProperty = $reflection->getProperty('data');
				$dataProperty->setAccessible(true);
				$data = $dataProperty->getValue($this->view);
				$data = array_merge($data, $vars);
				if(isset($data['data']) && $data['data'] instanceof Paginator){
					/**@var $paginator Paginator */
					$paginator = $data['data'];
					$data = array_merge($data, [
						'data'        => $paginator->items(),
						'total'       => $paginator->total(),
						'listRows'    => $paginator->listRows(),
						'currentPage' => $paginator->currentPage(),
						'lastPage'    => $paginator->lastPage(),
					]);
				}
				return Hint::result([], $data);
			}catch(\Exception $e){
				throw new \RuntimeException("错误的数据", 0, $e);
			}
		}
		/** @noinspection PhpUndefinedClassInspection */
		/** @noinspection PhpUndefinedMethodInspection */
		return parent::fetch($template, $vars, $config);
	}
}
